<template>
  <div class="voice-generation-container">
    <div class="btn-animate btn-animate__surround" @click="goToHome">
      <span>点击返回主页面</span>
    </div>
    <div class="header">
      <h1>语音合成</h1>
      <p>将文本转换为自然流畅的语音，支持九国语言和多种声音选择</p>
    </div>

    <div class="main-content">
      <!-- 翻译工具卡片 -->
      <div class="tool-card translation-card">
        <h2 class="card-title">
          <span class="icon">🌐</span>
          智能翻译助手
        </h2>
        <p class="card-desc">将中文文本翻译成目标语言，获得更好的语音合成效果</p>
        
        <div class="translation-content">
          <div class="input-section">
            <div class="input-group">
              <label>中文文本</label>
              <textarea 
                v-model="translationForm.chineseText" 
                placeholder="请输入要翻译的中文文本，例如：欢迎使用AI语音合成助手..."
                rows="3"
              ></textarea>
              <div class="char-count">{{ translationForm.chineseText.length }}/500</div>
            </div>
            
            <div class="input-group">
              <label>目标语言</label>
              <el-select v-model="translationForm.targetLang" placeholder="请选择目标语言" class="full-width">
                <el-option
                  v-for="(name, code) in translationLanguages"
                  :key="code"
                  :label="name"
                  :value="code"
                />
              </el-select>
            </div>
            
            <div class="translate-actions">
              <button 
                class="translate-btn el-button el-button--primary"
                @click="translateText"
                :disabled="!translationForm.chineseText.trim() || isTranslating"
              >
                <span v-if="!isTranslating">🔄 翻译成目标语言</span>
                <span v-else>⏳ 翻译中...</span>
              </button>
              
              <button 
                class="copy-btn el-button el-button--success"
                @click="copyTranslatedText"
                v-if="translationForm.translatedText"
              >
                📋 复制结果
              </button>
            </div>
          </div>

          <div class="result-section" v-if="translationForm.translatedText">
            <div class="input-group">
              <label>翻译结果</label>
              <textarea 
                v-model="translationForm.translatedText" 
                :readonly="true"
                rows="3"
                placeholder="翻译结果将显示在这里"
              ></textarea>
            </div>
            
            <div class="use-translation">
              <button class="use-btn el-button el-button--info" @click="useTranslationForSpeech">
                🎯 用于语音合成
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 语音合成区域 -->
      <div class="tool-card speech-card">
        <h2 class="card-title">
          <span class="icon">🗣️</span>
          AI语音合成
        </h2>
        <p class="card-desc">将文本转换为自然流畅的语音，支持多种语言和声音选择</p>

        <div class="speech-content">
          <!-- 输入区域 -->
          <div class="input-section">
            <div class="form-group">
              <label>输入文本</label>
              <el-input
                v-model="inputText"
                type="textarea"
                :rows="6"
                placeholder="请输入要转换为语音的文本内容，或通过上方翻译工具生成..."
                maxlength="5000"
                show-word-limit
              />
            </div>

            <div class="form-row">
              <div class="form-group">
                <label>🗣️选择语言</label>
                <el-select v-model="selectedLanguage" placeholder="请选择语言" class="full-width" @change="suggestTranslationLanguage">
                  <el-option
                    v-for="(voice, key) in languages"
                    :key="key"
                    :label="key"
                    :value="key"
                  />
                </el-select>
              </div>

              <div class="form-group">
                <label>声音类型</label>
                <el-tag type="info" class="voice-tag">
                  {{ getVoiceType(selectedLanguage) }}
                </el-tag>
              </div>
            </div>

            <div class="form-group">
              <label>语速调节</label>
              <div class="slider-container">
                <el-slider
                  v-model="speechRate"
                  :min="0.5"
                  :max="2"
                  :step="0.1"
                  :marks="{0.5: '慢', 1: '正常', 2: '快'}"
                />
                <span class="rate-value">{{ speechRate }}x</span>
              </div>
            </div>

            <div class="action-buttons">
              <el-button
                type="primary"
                size="large"
                @click="generateSpeech"
                :loading="isGenerating"
                :disabled="!inputText.trim()"
                class="generate-btn"
              >
                <i class="el-icon-microphone"></i>
                {{ isGenerating ? '生成中...' : '开始生成' }}
              </el-button>

              <el-button
                v-if="audioUrl"
                type="success"
                size="large"
                @click="playAudio"
                class="play-btn"
              >
                <i class="el-icon-video-play"></i>
                播放音频
              </el-button>
            </div>
          </div>

          <!-- 输出区域 -->
          <div class="output-section" v-if="audioUrl">
            <div class="audio-player">
              <h3>音频预览</h3>
              <audio
                ref="audioPlayer"
                :src="audioUrl"
                controls
                class="audio-controls"
              ></audio>
            </div>

            <div class="download-section">
              <el-button
                type="primary"
                plain
                @click="downloadAudio"
                class="download-btn"
              >
                <i class="el-icon-download"></i>
                下载音频
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 提示信息 -->
    <el-alert
      v-if="message"
      :title="message.text"
      :type="message.type"
      :closable="false"
      class="message-alert"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

const router = useRouter();

// 数据
const inputText = ref('');
const selectedLanguage = ref('');
const speechRate = ref(1);
const isGenerating = ref(false);
const isTranslating = ref(false);
const audioUrl = ref('');
const audioPlayer = ref(null);
const message = ref(null);

// 翻译表单数据
const translationForm = reactive({
  chineseText: '',
  translatedText: '',
  sourceLang: 'zh',
  targetLang: 'en' // 默认英语
});

// 支持翻译的语言列表
const translationLanguages = ref({
  'en': '英语 (English)',
  'ja': '日语 (Japanese)',
  'ko': '韩语 (Korean)',
  'fr': '法语 (French)',
  'de': '德语 (German)',
  'es': '西班牙语 (Spanish)',
  'ru': '俄语 (Russian)',
  'pt': '葡萄牙语 (Portuguese)',
  'it': '意大利语 (Italian)',
  'ar': '阿拉伯语 (Arabic)',
  'hi': '印地语 (Hindi)',
  'th': '泰语 (Thai)',
  'vi': '越南语 (Vietnamese)'
});

// 语言配置
const languages = ref({
    '普通话 (中国大陆)-Xiaoxiao-女': 'zh-CN-XiaoxiaoNeural',
    '普通话 (中国大陆)-Yunyang-男': 'zh-CN-YunyangNeural',
    '普通话 (中国大陆)-Xiaoyi-女': 'zh-CN-XiaoyiNeural',
    '东北话 (中国大陆)-Xiaobei-女': 'zh-CN-liaoning-XiaobeiNeural',
    '中原官话 (陕西)-Xiaoni-女': 'zh-CN-shaanxi-XiaoniNeural',
    '粤语 (中国香港)-HiuMaan-女': 'zh-HK-HiuMaanNeural',
    '粤语 (中国香港)-WanLung-男': 'zh-HK-WanLungNeural',
    '台湾普通话-HsiaoChen-女': 'zh-TW-HsiaoChenNeural',
    '台湾普通话-YunJhe-男': 'zh-TW-YunJheNeural',
    '英语 (美国)-Jenny-女': 'en-US-JennyNeural',
    '英语 (美国)-Guy-男': 'en-US-GuyNeural',
    '英语 (英国)-Libby-女': 'en-GB-LibbyNeural',
    '英语 (英国)-Thomas-男': 'en-GB-ThomasNeural',
    '日语 (日本)-Nanami-女': 'ja-JP-NanamiNeural',
    '日语 (日本)-Keita-男': 'ja-JP-KeitaNeural',
    '韩语 (韩国)-Sun-Hi-女': 'ko-KR-SunHiNeural',
    '法语 (法国)-Eloise-女': 'fr-FR-EloiseNeural',
    '法语 (法国)-Henri-男': 'fr-FR-HenriNeural',
    '德语 (德国)-Katja-女': 'de-DE-KatjaNeural',
    '德语 (德国)-Conrad-男': 'de-DE-ConradNeural',
    '西班牙语 (西班牙)-Elvira-女': 'es-ES-ElviraNeural',
    '西班牙语 (西班牙)-Alvaro-男': 'es-ES-AlvaroNeural',
    '印地语 (印度)-Madhur-男': 'hi-IN-MadhurNeural',
    '印地语 (印度)-Swara-女': 'hi-IN-SwaraNeural',
    '葡萄牙语 (巴西)-Francisca-女': 'pt-BR-FranciscaNeural',
    '葡萄牙语 (巴西)-Antonio-男': 'pt-BR-AntonioNeural',
    '俄语 (俄罗斯)-Svetlana-女': 'ru-RU-SvetlanaNeural',
    '俄语 (俄罗斯)-Dmitry-男': 'ru-RU-DmitryNeural'
  });

// 获取声音类型
const getVoiceType = (languageKey) => {
  if (!languageKey) return '';
  if (languageKey.includes('男')) return '男声';
  if (languageKey.includes('女')) return '女声';
  return '未知';
};

// 根据语音语言建议翻译目标语言
const suggestTranslationLanguage = (languageKey) => {
  if (!languageKey) return;
  
  // 根据选择的语言建议目标翻译语言
  if (languageKey.includes('英语')) {
    translationForm.targetLang = 'en';
  } else if (languageKey.includes('日语')) {
    translationForm.targetLang = 'ja';
  } else if (languageKey.includes('韩语')) {
    translationForm.targetLang = 'ko';
  } else if (languageKey.includes('法语')) {
    translationForm.targetLang = 'fr';
  } else if (languageKey.includes('德语')) {
    translationForm.targetLang = 'de';
  } else if (languageKey.includes('西班牙语')) {
    translationForm.targetLang = 'es';
  } else if (languageKey.includes('印地语')) {
    translationForm.targetLang = 'hi';
  } else if (languageKey.includes('葡萄牙语')) {
    translationForm.targetLang = 'pt';
  } else if (languageKey.includes('俄语')) {
    translationForm.targetLang = 'ru';
  } else {
    translationForm.targetLang = 'en'; // 默认英语
  }
};

// 翻译功能
const translateText = async () => {
  if (!translationForm.chineseText.trim()) {
    ElMessage.warning('请输入要翻译的文本');
    return;
  }
  
  isTranslating.value = true;
  try {
    const response = await fetch('http://localhost:5000/api/translate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        text: translationForm.chineseText,
        source_lang: translationForm.sourceLang,
        target_lang: translationForm.targetLang
      })
    });
    
    const data = await response.json();
    
    if (data.success) {
      translationForm.translatedText = data.translated_text;
      ElMessage.success('翻译成功！');
    } else {
      ElMessage.error('翻译失败: ' + (data.error || '未知错误'));
    }
  } catch (error) {
    ElMessage.error('翻译请求失败: ' + error.message);
  } finally {
    isTranslating.value = false;
  }
};

// 复制翻译结果
const copyTranslatedText = async () => {
  try {
    await navigator.clipboard.writeText(translationForm.translatedText);
    ElMessage.success('已复制到剪贴板');
  } catch (err) {
    ElMessage.error('复制失败，请手动选择复制');
  }
};

// 使用翻译结果
const useTranslationForSpeech = () => {
  if (translationForm.translatedText) {
    inputText.value = translationForm.translatedText;
    ElMessage.success('已将翻译结果用于语音合成');
  }
};

// 生成语音
const generateSpeech = async () => {
  if (!inputText.value.trim()) {
    ElMessage.warning('请输入要转换的文本');
    return;
  }

  isGenerating.value = true;
  message.value = null;

  try {
    const response = await fetch('http://localhost:5000/api/voice-generation', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        text: inputText.value,
        language: selectedLanguage.value,
        rate: speechRate.value
      })
    });

    if (!response.ok) {
      throw new Error('生成失败');
    }

    const blob = await response.blob();
    audioUrl.value = URL.createObjectURL(blob);
    
    ElMessage.success('语音生成成功！');
  } catch (error) {
    ElMessage.error('语音生成失败，请稍后重试');
    console.error('Error:', error);
  } finally {
    isGenerating.value = false;
  }
};

// 播放音频
const playAudio = () => {
  if (audioPlayer.value) {
    audioPlayer.value.play();
  }
};

// 下载音频
const downloadAudio = () => {
  if (!audioUrl.value) return;
  
  const link = document.createElement('a');
  link.href = audioUrl.value;
  link.download = `语音_${new Date().getTime()}.mp3`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

// 返回首页
const goToHome = () => {
  router.push('/');
};

// 初始化
onMounted(() => {
  // 设置默认语言
  const keys = Object.keys(languages.value);
  if (keys.length > 0) {
    selectedLanguage.value = keys[0];
  }
});
</script>

<style scoped>
@import '../assets/VoiceGeneration.css';
</style>
